﻿using Domain.Config;
using Domain.Event;
using Domain.IRepositorys;
using Domain.Model;
using Domain.Services;
using Infrastructure.DomainEvent;
using Infrastructure.Error;
using Infrastructure.UniOfWorkBase;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Utility;

namespace Application.Event
{
    /// <summary>
    /// 商家升级事件
    /// </summary>
    public class PayUpLevelByTraderEventHandler : IDomainEventHandler<PayUpLevelByTraderEvent>
    {
        public IWalletRepository walletRepository { get; set; }
        public IUserRepository userRepository { get; set; }
        public IInviteLogRepository inviteLogRepository { get; set; }
        public IEFUnitOfWork efUnitOfWork { get; set; }
        public UserService userService { get; set; }
        public FeeService feeService { get; set; }
        public MsgPulishService msgPulishService { get; set; }
        public ILogger<PayUpLevelByTraderEventHandler> _logger { get; set; }
        public override Task HandleAysnc(PayUpLevelByTraderEvent domainEvent, CancellationToken cancellationToken = default)
        {
            try
            {
                int fee = SystemConfig.GetConfigByTime<int>("系统配置", $"等级.超级商人.{domainEvent.Month}个月", TimeSpan.FromDays(1));

                var r = userService.PayUpLevelByTrader(domainEvent.UserID, domainEvent.Month, domainEvent.PayID, fee);// domainEvent.PayMoney

                //上线收益计算
                var r2 = feeService.HandleUserUpSuperorReward(domainEvent.UserID, fee);// r.PayMoney

                efUnitOfWork.Commit();


                msgPulishService.SendMsg(domainEvent.UserID,"升级成功", $"升级超级商人{domainEvent.Month}个月成功!");
            }
            catch (BizException ex)
            {
                //任务支付失败通知用户
                msgPulishService.SendMsg(domainEvent.UserID,"升级失败", $"升级失败,{ex.Message}!");

                _logger.LogException(ex, domainEvent);
            }


            return Task.CompletedTask;
        }
    }
}
